package com.automannn.websocketmqtt.rocketmq.nodeA.config;

import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.io.UnsupportedEncodingException;
import java.util.List;

/**
 * @author chenkh
 * @time 2020/11/2 10:01
 */
@Component
public class RocketMQConsumeMsgListener implements MessageListenerConcurrently {
    public static final Logger LOGGER = LoggerFactory.getLogger(RocketMQConsumeMsgListener.class);

    @Override
    public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
        if (CollectionUtils.isEmpty(list)){
            LOGGER.info("mq接收消息为空，直接返回成功");
            return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
        }
        MessageExt messageExt = list.get(0);
        LOGGER.info("mq接收到的消息为:"+messageExt.toString());

        try{
            String topic = messageExt.getTopic();
            String tags = messageExt.getTags();
            String body = new String(messageExt.getBody(),"utf-8");

            LOGGER.info("mq消息topic={},tags={},消息内容={}",topic,tags,body);
        } catch (UnsupportedEncodingException e) {
            LOGGER.error("获取mq消息内容异常!");
        }
        return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
    }
}
